<?php
//error_log("ran\n", 3, "/var/www/vhosts/vps4291.unoeuro-server.com/httpdocs/_cj/errors.log");
define('DS', DIRECTORY_SEPARATOR);
define('GOOGLE_API_KEY', "AIzaSyBLUIq6qEZPK2Ppwsz-XyoT0vxE4b6nehE");
define('_VEXEC', 1);
define('JPATH_PLATFORM', dirname(__FILE__));
define('JPATH_BASE', dirname(__FILE__));


//*DEBUG
ini_set("display_errors", 1);
error_reporting(E_ALL); 
//*/


//Joomla db handlers
include(JPATH_BASE.DS."..".DS."libraries".DS."loader.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."log".DS."log.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."log".DS."entry.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."utilities".DS."date.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."error".DS."error.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."methods.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."factory.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."registry".DS."registry.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."base".DS."object.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."language".DS."language.php");
include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."database".DS."exception.php");
	include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."database".DS."database.php");
		include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."database".DS."database".DS."mysql.php");
			include(JPATH_BASE.DS."..".DS."libraries".DS."joomla".DS."database".DS."database".DS."mysqli.php");

	function mySql2PhpTime($sqlDate){
		$arr = date_parse($sqlDate);
		return mktime($arr["hour"],$arr["minute"],$arr["second"],$arr["month"],$arr["day"],$arr["year"]);
	}

	function php2MySqlTime($date){
		return date("Y-m-d H:i:00", $date);
	}

$db=JDatabase::getInstance(array(
	'driver' => "mysqli",
	'host' => "localhost",
	'user' => "fpdbu",
	'password' => "6PKPRKK74wEDdzPD",
	'database' => "fitplan_dk",
	'prefix' => "efdsh"
	));


//FORCE timezone
//date_default_timezone_set("Asia/Ho_Chi_Minh");
date_default_timezone_set("Europe/Copenhagen");


//INIT
$queueA=array();
$queueI=array();
$devs=array();
$ids=array();
$now=time();
//$now=strtotime(date("2014-04-17 15:00"));

//MAIN flow

$cmp	=strtotime(date("Y-m-d H:i",$now));//send date
$tcmp	=date("H:i", $cmp);//send time

//[V] we run late 1 min, set back to compare
//if( intval(date("i", $cmp)) <= 30 )
//	$tcmp = date("H:30", $cmp);
//else if( intval(date("i", $cmp)) > 30 )
//	$tcmp = date("H:00", strtotime("+1 hour", $cmp));
//

$monday =  date("d", $cmp) - date('N', $cmp) + 1;
$icmp = mktime(0,0,0,date("m", $cmp), $monday, date("Y", $cmp));//to calc week
$iday = (int)date("N", $cmp);//to cmp day

//CLEAN obsolete devices
	$db->setQuery("SELECT d.id FROM `#___user_iddevice` d LEFT JOIN `#___users` u on d.id=u.id WHERE u.id IS NULL");
	$rows=$db->loadResultArray();
	if($rows){
		$rows=implode(",", $rows);
		$db->setQuery("DELETE FROM `#___user_iddevice` WHERE id IN ($rows)");
		$db->query();
		unset($rows);
	}
//

//All active devices
	$db->setQuery("SELECT SQL_NO_CACHE d.*, registerDate
FROM `#___user_iddevice` d
INNER JOIN `#___users` u
ON d.id=u.id
WHERE isActive > ''
AND id_device > ''");
	$devs=$db->loadObjectList();
//
//echo '<pre>',print_r($devs),'</pre>';
//Abort if no device
if(!$devs)
	die;
	
//Restructure
	foreach($devs as $k => $v)
	{
		$v->registerDate=mySql2PhpTime($v->registerDate);

		//move regDate to Monday of current week
		$monday =  date("d", $v->registerDate) - date('N', $v->registerDate) + 1;
		$v->registerDate = mktime(0,0,0,date("m", $v->registerDate), $monday, date("Y", $v->registerDate));

		$devs[$v->id]=$v;
		$ids[]=$v->id;
		unset($devs[$k]);
	}


//All notifications by student ids
	$db->setQuery("SELECT SQL_NO_CACHE *
FROM `#___jqcalendar`
WHERE id_student IN (".implode(',', $ids).")
AND type=0");
	$row=$db->loadObjectList();
//echo '<pre>',print_r($row),'</pre>';

	//scan through items
	foreach($row as $k => $v){

		$sDate=mySql2PhpTime($v->StartTime);
		$xTime=date("H:i", $sDate);//startDate w/o time
		if($devs[$v->id_student]->isActive=="A")
			$queue= &$queueA;
		else
			$queue= &$queueI;

		if($sDate == $cmp)//event start in time
			$queue[$devs[$v->id_student]->id_device] = array($v->Subject, $v->Id);

		if($v->RecurringRule)
		{
			$v->RecurringRule=json_decode($v->RecurringRule);
			$week=round(($icmp - $devs[$v->id_student]->registerDate)/604800);//number of week

			foreach($v->RecurringRule->weeks as $w)
			if($week==$w)
			{
				foreach($v->RecurringRule->weekdays as $d)
				if($iday==$d)
				{
					if($xTime==$tcmp)
					{//clone OK
						if(!isset($queue[$devs[$v->id_student]->id_device]))
							$queue[$devs[$v->id_student]->id_device] = array($v->Subject, $v->Id);
					}

				}//end day

			}//end week

		}//end rules

	}//end scan
//error_log(print_r($queueI,true)."\r\n".date("d.m H:i",$now), 3, "/var/www/vhosts/vps4291.unoeuro-server.com/httpdocs/_cj/errors.log");


//SEND ANDROID
if( $queueA ){

include("GCM.php");
$gcm = new GCM();

	foreach($queueA as $k => $msg){

		$adt_ids = array($k);//max 1000 IDs
		$msg = array(
				"message" => $msg[0],
				"questionId" => $msg[1]
			);

		$result = $gcm->send_notification($adt_ids, $msg);

		echo $msg["questionId"],"[$result]";

	}

}


//SEND iPHONE
if( $queueI ){

	$passphrase = 'alpha9173';

	$ctx = stream_context_create(
	array('ssl' => array(
			'local_cert'	=> '/var/www/vhosts/vps4291.unoeuro-server.com/httpdocs/_cj/ck.pem',
			'passphrase'	=> $passphrase)));

// Open a connection to the APNS server
	$fp = stream_socket_client(
		'ssl://gateway.push.apple.com:2195', $err,
		$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

	echo 'Connected to APNS' . PHP_EOL;

	foreach($queueI as $k => $msg){

	
		$body['aps'] = array(
	'alert' => $msg[0],
	'badge' => 1,
	'questionId' => intval($msg[1]),
	'sound' => 'default'
	);

// Encode the payload as JSON
		$payload = json_encode($body);

// Build the binary notification
		$msg = chr(0) . pack('n', 32) . pack('H*', $k) . pack('n', strlen($payload)) . $payload;

		// Send it to the server
		$result = fwrite($fp, $msg, strlen($msg));
		fclose($fp);

		echo ($result) ? "[ok]" . PHP_EOL : "[failed]" . PHP_EOL;

	}

}
///MAIN
//echo date("d.m.Y H:i", $now);